package com.example.spring.security.demo.component;

import com.alibaba.fastjson.JSON;
import com.example.spring.security.demo.entity.ResponseResult;
import com.example.spring.security.demo.utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName MyAccessDeniedHandler
 * @Description 用户权限验证失败处理
 * @Author lichuanqi
 * @Date 2022/5/16 13:57
 * @Version 1.0
 **/
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException)
            throws IOException, ServletException {
        System.out.println("#############MyAccessDeniedHandler#############");
        ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(), "权限不足");
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}
